package com.thjk.bdf.preloan.web.controller;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.common.hash.Hashing;
import com.thjk.bdf.common.base.BasicResp;
import com.thjk.bdf.common.enmus.ServiceEnum;
import com.thjk.bdf.common.entity.ApplyOrder;
import com.thjk.bdf.preloan.web.config.BdFConfig;
import com.thjk.bdf.preloan.web.util.SeesionUtils;
import com.thjk.bdf.service.OrderService;

/**
 * 产品介绍页
 * @author Sonny
 *
 */
@Controller
public class LoginController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private BdFConfig bdFConfig;
	@Autowired
	private OrderService orderService;
	
	/**
	 * 
	 *loanApply:(). 申请入口
	 * @return
	 */
	@RequestMapping(value="/bdfLoanProduct")
	public String sjdLoanProduct(HttpServletRequest request, HttpServletResponse response){

		return "bdf/productInfo";
		
	}
	
	/**
	    *   我的贷款
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/myLoanRecord", method = RequestMethod.GET)
	public String myLoanRecord(Model model,HttpServletRequest request, HttpServletResponse response) {
		try {
			List<ApplyOrder> list = orderService.selectByPhone(SeesionUtils.getData().getPhone());
			BasicResp resp = new BasicResp();
			if(list==null||list.isEmpty()){
				resp.setCode(ServiceEnum.APPLY_INFO_MISSING.getCode());
				resp.setMessage(ServiceEnum.APPLY_INFO_MISSING.getDesc());
				return "bdf/noApplyMind";
			}
			//提交授信申请 组装大数url
			String url = bdFConfig.getBdUrl();
			String userName= SeesionUtils.getData().getPhone();
			String channel = bdFConfig.getApiKey();
			Long time =System.currentTimeMillis();
			
			String sign=Hashing.sha256().hashString(userName+bdFConfig.getApiSecret()+time,StandardCharsets.UTF_8).toString();
			 
			StringBuffer redicretUrl = new StringBuffer(url);
			redicretUrl.append("username="+userName);
			redicretUrl.append("&channel="+channel);
			redicretUrl.append("&time="+time);
			redicretUrl.append("&sign="+sign);
			redicretUrl.append("&pageFlag="+bdFConfig.getQueryPageFlag());
//	 		String redicretUrl = url+"?username="+userName+"&channel="+channel+"&time="+time+"&sign="
//	 				+sign+"&pageFlag="+bdFConfig.getApplyPageFlag();
	 		logger.info("bdf url :"+redicretUrl);
			response.sendRedirect(redicretUrl.toString());
			return null;

		} catch (IOException e) {
			logger.error("跳转大树我的贷款页异常：{}", e);
		};
		return null;
	}
}
